package com.yy.ttmodule.udp;

import android.util.Log;

public class UdpDataUtil {

    private static final String TAG = "UdpData";

    private UdpDataUtil() {

    }

    protected static synchronized int calCRCBySum(byte[] pSrcBuf, int len) {
        int crc;
        int i = 0;
        int crcReg = 0;

        while (len-- != 0) {
            crcReg += pSrcBuf[i];
            i++;
        }

        crc = 0x00000000 - crcReg;

        return crc & 0x0FF;
    }

    protected static synchronized int comUnPackage(byte[] pSrcBuf, byte[] pResultBuf, int rawPackageLen) {
        int receivedCRC;
        int CRCByCal;

        for (int i = 0; i < rawPackageLen; i++ ) {
            pResultBuf[i] = pSrcBuf[i];
        }

        receivedCRC = pSrcBuf[rawPackageLen - 1] & 0x0FF;
//        Log.d(TAG,"comUnPackage = " +
//                ConvertData.byteArrayToHexString(pResultBuf, rawPackageLen));


        // 包头、包尾及CRC不校验
        CRCByCal = calCRCBySum(ConvertData.subBytes(pResultBuf, 0, rawPackageLen - 1), rawPackageLen - 1);
        Log.d(TAG,"comUnPackage CRCByCal = " + CRCByCal + " receivedCRC " + receivedCRC);

        if (receivedCRC == CRCByCal) {
            // 如果成功，则返回长度
            return rawPackageLen;
        } else {
            return -1;
        }
    }

    public static synchronized int comPackage(byte[] pSrcBuf, byte[] pResultBuf, int len) {

        int crc = calCRCBySum(ConvertData.subBytes(pSrcBuf, 0, len), len); // 校验码
        pSrcBuf[len] = (byte) (crc & 0x0FF);

        // 加入CRC后，长度增加1
        len += 1;

        for (int i = 0; i < len; i++ ) {
            pResultBuf[i] = pSrcBuf[i];
        }

        return len;
    }
}
